package com.darrenchan.leetcode;

import java.util.Arrays;

/**
 * @Desc
 * @Author chenchi03
 * @CreateTime 2020-04-20 12:15
 */
public class QLint59 {
    public int threeSumClosest(int[] numbers, int target) {
        if(numbers == null || numbers.length < 3) {
            return 0;
        }

        Arrays.sort(numbers);
        int diff = Integer.MAX_VALUE;
        int res = 0;
        for (int i = 0; i < numbers.length - 2; i++) {
            int left = i + 1, right = numbers.length - 1;
            while (left < right) {
                if(numbers[i] + numbers[left] + numbers[right] < target) {
                    diff = Math.min(diff, target - numbers[left] - numbers[right] - numbers[i]);
                    if(diff == target - numbers[left] - numbers[right] - numbers[i]) {
                        res = numbers[left] + numbers[right] + numbers[i];
                    }
                    left++;
                } else {
                    diff = Math.min(diff, numbers[left] + numbers[right] + numbers[i] - target);
                    if(diff == numbers[left] + numbers[right] + numbers[i] - target) {
                        res = numbers[left] + numbers[right] + numbers[i];
                    }
                    right--;
                }
            }

        }

        return res;
    }
}
